<template>
  <div id="selectionlist">
    <el-dialog title="人员信息详情" :visible.sync="personDetailVisible" width="80%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false">
      <personInfo v-bind:personId='personId' :hidemoredetail="true"></personInfo>
    </el-dialog>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">系统首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/selection' }">干部选任</el-breadcrumb-item>
      <el-breadcrumb-item >动议</el-breadcrumb-item>
    </el-breadcrumb>
    <el-dialog :title="postFormTitle" :visible.sync="postFormVisible" top="20px" width="95%" @open="opendialog" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="postForm" :model="postForm" label-width="90px" :rules="postFormRules" inline>
        <h1 style="margin-bottom:20px;">岗位信息</h1>
        <el-form-item label="岗位单位" prop="unitname">
          <el-autocomplete style="width:400px" v-model="postForm.unitname" @change.native="getUnitType(0)" @select="getUnitType(0)" :fetch-suggestions="querySearch" placeholder="请输入单位名称关键字" :trigger-on-focus="false" ></el-autocomplete>
        </el-form-item>
        <div style="clear:both"></div>
        <el-form-item label="职务" prop="post" v-loading="postloading">
          <el-select v-model="postForm.post" placeholder="请选择" style="width:150px;">
            <el-option label="无调整" value=""></el-option>
            <el-option v-for="(item, index) in postlist" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职务描述" prop="jobDescription">
          <el-input v-model="postForm.jobDescription" style="width:150px;"></el-input>
        </el-form-item>
        <el-form-item label="职级" prop="postclass">
          <el-select v-model="postForm.postclass" placeholder="请选择" style="width:200px;">
            <el-option label="无调整" value=""></el-option>
            <el-option v-for="(item, index) in postclasslist" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <div style="clear:both"></div>
        <h1 style="margin-bottom:20px;">人选一</h1>
        <el-form-item label="动议类型" prop="changeType">
          <el-select v-model="postForm.changeType" placeholder="请选择" style="width:100px;" @change="checkIdCard1(postForm.idcardNo)">
            <el-option v-for="(item, index) in changeTypeList" :key="index" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="人选单位" prop="oldunitname">
          <el-autocomplete style="width:350px" v-model="postForm.oldunitname" @change.native="getUnitType(1)" @select="getUnitType(1)" :fetch-suggestions="querySearch" placeholder="请输入单位名称关键字" :trigger-on-focus="false" ></el-autocomplete>
        </el-form-item>
        <el-form-item label="姓名" prop="personname">
          <el-autocomplete style="width:260px" v-model="postForm.personname" :fetch-suggestions="searchPerson" placeholder="请输入人选姓名" :trigger-on-focus="false" @select="handleSelect1">
            <template slot-scope="{ item }">
              {{ item.value }}({{ item.idno }})
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="身份证号" prop="idcardNo">
          <el-input v-model="postForm.idcardNo" style="width:180px;" @input="checkIdCard1"></el-input>
        </el-form-item>
        <div style="clear:both"></div>
        <el-form-item label="目前职务" prop="oldpost" v-loading="postloading">
          <el-select v-model="postForm.oldpost" placeholder="请选择" style="width:150px;">
            <el-option label="无" value=""></el-option>
            <el-option v-for="(item, index) in postlist1" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职务描述" prop="currentJobDescription">
          <el-input v-model="postForm.currentJobDescription" style="width:150px;"></el-input>
        </el-form-item>
        <el-form-item label="目前职级" prop="oldpostclass">
          <el-select v-model="postForm.oldpostclass" placeholder="请选择" style="width:200px;">
            <el-option label="无" value=""></el-option>
            <el-option v-for="(item, index) in postclasslist" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-alert
          style="margin-bottom:5px;"
          v-if="warningText11Show"
          :title="warningText1"
          type="warning"
          effect="dark">
        </el-alert>
        <el-alert
          style="margin-bottom:5px;"
          v-if="warningText12Show"
          title="该人选正处于试用期"
          type="warning"
          effect="dark">
        </el-alert>
        <div style="clear:both"></div>
        <h1 style="margin-bottom:20px;">人选二</h1>
        <el-form-item label="动议类型" prop="changeType2">
          <el-select v-model="postForm.changeType2" placeholder="请选择" style="width:100px;" @change="checkIdCard2(postForm.idcardNo2)">
            <el-option v-for="(item, index) in changeTypeList" :key="index" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="人选单位" prop="oldunitname2">
          <el-autocomplete style="width:350px" v-model="postForm.oldunitname2" @change.native="getUnitType(2)" @select="getUnitType(2)" :fetch-suggestions="querySearch" placeholder="请输入单位名称关键字" :trigger-on-focus="false" ></el-autocomplete>
        </el-form-item>
        <el-form-item label="姓名" prop="personname2">
          <el-autocomplete style="width:260px" v-model="postForm.personname2" :fetch-suggestions="searchPerson2" placeholder="请输入人选姓名" :trigger-on-focus="false" @select="handleSelect2">
            <template slot-scope="{ item }">
              {{ item.value }}({{ item.idno }})
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="身份证号" prop="idcardNo2">
          <el-input v-model="postForm.idcardNo2" style="width:180px" @input="checkIdCard2"></el-input>
        </el-form-item>
        <div style="clear:both"></div>
        <el-form-item label="目前职务" prop="oldpost2" v-loading="postloading">
          <el-select v-model="postForm.oldpost2" placeholder="请选择" style="width:150px;">
            <el-option label="无" value=""></el-option>
            <el-option v-for="(item, index) in postlist2" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职务描述" prop="currentJobDescription">
          <el-input v-model="postForm.currentJobDescription2" style="width:150px;"></el-input>
        </el-form-item>
        <el-form-item label="目前职级" prop="oldpostclass2">
          <el-select v-model="postForm.oldpostclass2" placeholder="请选择" style="width:200px;">
            <el-option label="无" value=""></el-option>
            <el-option v-for="(item, index) in postclasslist" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-alert
          style="margin-bottom:5px;"
          v-if="warningText21Show"
          :title="warningText2"
          type="warning"
          effect="dark">
        </el-alert>
        <el-alert
          style="margin-bottom:5px;"
          v-if="warningText22Show"
          title="该人选正处于试用期"
          type="warning"
          effect="dark">
        </el-alert>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="postFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="postFormSubmit" :loading="postFormLoading">提交</el-button>
      </div>
    </el-dialog>
    <section class="wboxnoborder">
      <div :style="'height:'+tableHeight+'px'">
        <el-scrollbar style="height: calc(100% + 16px);">
          <div v-show="(step===0||step===1)&&inRoles('ROLE_chuzhang')">
            <el-radio-group v-model="status" @change="changestatus" style="margin:15px 0 0 15px" class="pointRadio">
              <el-radio-button label="正在办理的动议" border>
                <el-badge v-if="countnum1>0" :value="countnum1" class="item">正在办理的动议</el-badge>
              </el-radio-button>
              <el-radio-button label="待报出人选" border>
                <el-badge v-if="countnum2>0" :value="countnum2" class="item">待报出人选</el-badge>
              </el-radio-button>
              <el-radio-button label="已退回人选" border>
                <el-badge v-if="countnum3>0" :value="countnum3" class="item">已退回人选</el-badge>
              </el-radio-button>
            </el-radio-group>
          </div>
          <!--确定人选-->
          <div v-if="step===0">
            <el-table :data="personlist" highlight-current-row v-loading="listLoading" style="width: calc(100% - 40px);margin:15px" border>
              <el-table-column prop="realName" label="姓名" width="120">
              </el-table-column>
              <el-table-column prop="changeTypeText" label="动议类型" width="120">
              </el-table-column>
              <el-table-column label="动议岗位">
                <el-table-column prop="unitName" label="单位" show-overflow-tooltip></el-table-column>
                <el-table-column prop="jobName" label="职务" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column prop="jobLevel" label="职级" width="150" show-overflow-tooltip></el-table-column>
              </el-table-column>
              <el-table-column label="目前信息">
                <el-table-column prop="candidateUnit" label="目前单位" show-overflow-tooltip></el-table-column>
                <el-table-column prop="currentJob" label="目前职务" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column prop="currentLevel" label="目前职级" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="干部全方位情况" width="150">
                  <template slot-scope="scope">
                    <el-button size="small" @click="detail(scope.row.idcardNo)" type="primary">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template slot-scope="scope">
                  <el-button circle size="small" @click="edit(scope.row.postId)" type="primary" icon="el-icon-edit"></el-button>
                  <el-button circle size="small" @click="del(scope.row.id)" type="danger" icon="el-icon-delete"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" style="margin:0 0 15px 15px;" @click="addpost">新增岗位</el-button>
            <el-button type="success" @click="saveposts" :loading="loading1">确定人选</el-button>
          </div>
          <!--确定人选结束-->
          <!--动议内容-->
          <div v-if="step===1">
            <el-button type="primary" @click="exportdoc" style="margin:15px 15px 0;">导出动议签报</el-button>
            <el-table :data="personlist" highlight-current-row v-loading="listLoading" style="width: calc(100% - 40px);margin:15px" border>
              <el-table-column prop="realName" label="姓名" width="100">
              </el-table-column>
              <el-table-column prop="changeTypeText" label="动议类型" width="100">
              </el-table-column>
              <el-table-column label="动议岗位">
                <el-table-column prop="unitName" label="单位" show-overflow-tooltip></el-table-column>
                <el-table-column prop="jobName" label="职务" width="160" show-overflow-tooltip></el-table-column>
                <el-table-column prop="jobLevel" label="职级" width="120" show-overflow-tooltip></el-table-column>
              </el-table-column>
              <el-table-column label="目前信息">
                <el-table-column prop="candidateUnit" label="目前单位" show-overflow-tooltip></el-table-column>
                <el-table-column prop="currentJob" label="目前职务" width="160" show-overflow-tooltip></el-table-column>
                <el-table-column prop="currentLevel" label="目前职级" width="120" show-overflow-tooltip></el-table-column>
                <el-table-column label="干部全方位情况" width="140">
                  <template slot-scope="scope">
                    <!-- {{scope.row.idcardNo}} -->
                    <el-button size="small" @click="detail(scope.row.idcardNo)" type="primary">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column label="动议结果" width="200">
                <template slot-scope="scope">
                  <el-radio-group v-model="scope.row.passed" @change="changeThisRadio">
                    <el-radio :label="2">通过</el-radio>
                    <el-radio :label="1">未通过</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
            </el-table>
            <el-form ref="dongyiForm" :model="dongyiForm" label-width="150px" :rules="dongyiFormRules">
              <el-form-item label="上传附件" prop="file">
                <el-upload
                  class="upload-demo"
                  :action="this.$http.defaults.baseURL+this.$http.defaults.selectionAPI +'api/gen/file/upload/'"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  multiple
                  :on-success="getImportList"
                  :file-list="fileList"
                  :on-error='uploaderror'
                  with-credentials>
                  <el-button type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="党组会动议情况" prop="meetdate" style="float:left">
                <el-date-picker v-model="dongyiForm.meetdate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
              <el-form-item  prop="meetnum" inline label-width="0" style="float:left;margin-left:10px">
                第<el-input-number v-model="dongyiForm.meetnum" :min="1" :max="100" style="margin:0 10px;"></el-input-number>
                次党组会审议
              </el-form-item>
              <el-form-item label="部领导批示" prop="buleader" style="clear:both">
                <leaderOpinion :recordId="this.$route.params.id" recordTable="bus_change_proposal" :leaderType="1" :canEdit="true"></leaderOpinion>
              </el-form-item>
              <el-form-item label="司领导批示" prop="sileader">
                <leaderOpinion :recordId="this.$route.params.id" recordTable="bus_change_proposal" :leaderType="2" :canEdit="true"></leaderOpinion>
              </el-form-item>
              <el-form-item>
              <el-button type="success" @click="savedongyi" :loading="loading2">动议完成</el-button>
              </el-form-item>
            </el-form>
          </div>
          <!--动议内容结束-->
          <!--动议结果-->
          <div v-if="step===2">
            <el-button type="primary" @click="exportdoc" style="margin:15px 15px 0;">导出动议签报</el-button>
            <meetingDetail :downloadfiles="downloadfiles" :personlist="personlist" :dongyishowForm="dongyishowForm" :changeId="$route.params.id"></meetingDetail>
            <el-button type="primary" @click="backlist" style="margin-left:150px">返回</el-button>
          </div>
          <!--动议结果结束-->
        </el-scrollbar>
      </div>
    </section>
  </div>
</template>

<script>
import meetingDetail from './common/meetingDetail'
import leaderOpinion from './common/leaderOpinion'
import Qs from 'qs'
import personInfo from '@/person/Detail.vue'
export default {
  components: {
    meetingDetail,
    personInfo,
    leaderOpinion
  },
  data () {
    // var checkperson2 = (rule, value, callback) => {
    //   if ((this.postForm.oldunitname2 === '' || !this.postForm.oldunitname2) && (this.postForm.personname2 === '' || !this.postForm.personname2)) {
    //     callback()
    //   } else {
    //     if (this.postForm.oldunitname2 && this.postForm.oldunitname2 !== '' && this.postForm.personname2 && this.postForm.personname2 !== '' && this.postForm.oldpost2 && this.postForm.oldpost2 !== '' && this.postForm.oldpostclass2 && this.postForm.oldpostclass2 !== '') {
    //       callback()
    //     }
    //     callback(new Error('如果有两个人选，请将人选二的全部信息填写完整，如果只有一个人选，请不要填写人选二单位、姓名'))
    //   }
    // }
    return {
      warningText11Show: false,
      warningText12Show: false,
      warningText21Show: false,
      warningText22Show: false,
      postloading: false,
      countnum1: 0,
      countnum2: 0,
      countnum3: 0,
      step: 0,
      meeting: {
        meetingTime: '',
        meetingNumber: '',
        leaderOpinion: '',
        leader2Opinion: '',
        files: []
      },
      personlist: [],
      postForm: {
        unitname: '',
        post: '',
        postclass: '',
        personid: '',
        personname: '',
        idcardNo: '',
        changeType: '',
        oldunitname: '',
        oldpost: '',
        oldpostclass: '',
        personid2: '',
        personname2: '',
        idcardNo2: '',
        changeType2: '',
        oldunitname2: '',
        oldpost2: '',
        oldpostclass2: '',
        jobDescription: '',
        currentJobDescription: '',
        currentJobDescription2: ''
      },
      postFormRules: {
        // unitname: [{ required: true, message: '请输入岗位单位', trigger: 'blur' }],
        changeType: [{ required: true, message: '请选择动议类型', trigger: 'blur' }],
        oldunitname: [{ required: true, message: '请输入人选单位', trigger: 'blur' }],
        personname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        idcardNo: [{ required: true, message: '请输入身份证号', trigger: 'blur' }]

        // oldunitname2: [{ validator: checkperson2, trigger: 'blur' }],
        // personname2: [{ validator: checkperson2, trigger: 'blur' }],
        // oldpost2: [{ validator: checkperson2, trigger: 'blur' }],
        // oldpostclass2: [{ validator: checkperson2, trigger: 'blur' }]
      },
      totalnum: 0,
      pageNum: 1,
      pageSize: 20,
      listLoading: false,
      changeSizeFlag: false,
      tableHeight: 100,
      postFormVisible: false,
      postlist: [],
      postlist1: [],
      postlist2: [],
      postclasslist: [],
      postFormLoading: false,
      postFormTitle: '新增岗位',
      editpostid: 0,
      fileList: [],
      files: [],
      dongyiForm: {
        meetdate: '',
        meetnum: '',
        buleader: '',
        sileader: ''
      },
      dongyiFormRules: {
        meetdate: [{ required: true, message: '请输入党组会时间', trigger: 'blur' }],
        meetnum: [{ required: true, message: '请输入第几次党组会', trigger: 'blur' }]
      },
      status: '',
      dongyishowForm: {
        meetdate: '',
        meetnum: '',
        buleader: '',
        sileader: ''
      },
      downloadfiles: [],
      personDetailVisible: false,
      personId: '',
      loading1: false,
      loading2: false,
      changeTypeList: []
    }
  },
  methods: {
    checkIdCard1 (idCard) {
      this.warningText11Show = false
      this.warningText12Show = false
      this.postFormLoading = true
      this.$http
        .get(this.$http.defaults.selectionAPI + `api/selection/syspost/getPostListByIdCard?idCard=` + idCard)
        .then(response => {
          this.postFormLoading = false
          if (response.data.length > 1 && this.postForm.changeType === '1504') {
            // this.$message({
            //   message: '该人选有多个职务：' + response.data.join('、'),
            //   type: 'warning'
            // })
            this.warningText1 = '该人选有多个职务：' + response.data.join('、')
            this.warningText11Show = true
          }
          if (response.data.find(item => item.indexOf('试用') > -1)) {
            // this.$message({
            //   message: '该人选正处于试用期',
            //   type: 'warning'
            // })
            this.warningText12Show = true
          }
        })
        .catch(function () {
        })
    },
    checkIdCard2 (idCard) {
      this.warningText21Show = false
      this.warningText22Show = false
      this.postFormLoading = true
      this.$http
        .get(this.$http.defaults.selectionAPI + `api/selection/syspost/getPostListByIdCard?idCard=` + idCard)
        .then(response => {
          this.postFormLoading = false
          if (response.data.length > 1 && this.postForm.changeType2 === '1504') {
            // this.$message({
            //   message: '该人选有多个职务：' + response.data.join('、'),
            //   type: 'warning'
            // })
            this.warningText2 = '该人选有多个职务：' + response.data.join('、')
            this.warningText21Show = true
          }
          if (response.data.find(item => item.indexOf('试用') > -1)) {
            // this.$message({
            //   message: '该人选正处于试用期',
            //   type: 'warning'
            // })
            this.warningText22Show = true
          }
        })
        .catch(function () {
        })
    },
    changeThisRadio (val) {
      if (val === 1) {
        this.$message({
          message: '此操作将终止改人选选任工作',
          type: 'warning'
        })
      }
    },
    inRoles (str) {
      console.log(str)
      let arr = JSON.parse(localStorage.getItem('Roles'))
      // arr = 'aaabbROLE_admin'
      if (arr.indexOf(str) === -1) {
        return false
      } else {
        return true
      }
    },
    persondetail (id) {
      this.personDetailVisible = true
      this.personId = id
    },
    detail (idcardNo) {
      this.$http
        .get(this.$http.defaults.selectionAPI + `api/selection/jiben/getIdByIdCardNo?idcard=` + idcardNo)
        .then(response => {
          if (response.data.success) {
            if (response.data.result) {
              this.persondetail(response.data.result)
            } else {
              this.$message({
                message: '无此人选的干部全方位情况',
                type: 'error'
              })
            }
          } else {
            this.$message({
              message: '查询失败:无此人选的干部全方位情况',
              type: 'error'
            })
          }
        })
        .catch(function () {
          this.$message({
            message: '查询失败:无此人选的干部全方位情况',
            type: 'error'
          })
        })
    },
    handleSelect1 (item) {
      this.checkIdCard1(item.idno)
      console.log('selectitem')
      console.log(item.idno)
      this.postForm.idcardNo = item.idno
    },
    handleSelect2 (item) {
      this.checkIdCard2(item.idno)
      console.log('selectitem')
      console.log(item.idno)
      this.postForm.idcardNo2 = item.idno
    },
    backlist () {
      this.$router.push({path: '/selection/'})
    },
    getjob () {
      this.$http
        .post(this.$http.defaults.selectionAPI + `api/selection/syspost/list`, {})
        .then(response => {
          this.postlist = response.data
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    getjobLevel () {
      this.$http
        .get(this.$http.defaults.selectionAPI + `api/selection/syspostclass/list`)
        .then(response => {
          this.postclasslist = response.data
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    getChangeType () {
      this.$http
        .get(this.$http.defaults.selectionAPI + `api/sysDict/getByCode?code=15`)
        .then(response => {
          if (response.data.success) {
            this.changeTypeList = response.data.result
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    changestatus () {
      if (this.status === '正在办理的动议') {
        this.$router.push({path: '/selection/dongyilist/'})
      }
      if (this.status === '待报出人选') {
        this.$router.push({path: '/selection/dongyihou/'})
      }
      if (this.status === '已退回人选') {
        this.$router.push({path: '/selection/dongyifinish/'})
      }
    },
    handleRemove (file, fileList) {
      let newfiles = []
      for (let i = 0; i < this.files.length; i++) {
        if (this.files[i].fileName + '.' + this.files[i].fileType !== file.name) {
          newfiles.push(this.files[i])
        }
      }
      this.files = newfiles
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    getImportList (res) {
      if (res.success) {
        this.$message({
          message: '上传成功！' + res.message,
          type: 'success'
        })
        this.files.push(res.result[0])
      } else {
        console.log(res.message)
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    uploaderror (err) {
      console.log('具体错误')
      console.log(err)
      this.$message({
        message: '上传失败:' + err,
        type: 'error'
      })
    },
    opendialog () {
      this.warningText11Show = false
      this.warningText12Show = false
      this.warningText21Show = false
      this.warningText22Show = false
      if (this.$refs['postForm']) {
        this.$refs['postForm'].resetFields()
      }
      this.$nextTick(() => {
        if (this.editpostid > 0) {
          this.setform(this.editpostid)
        }
      })
    },
    edit (postid) {
      this.editpostid = postid
      this.postFormVisible = true
      this.postFormTitle = '编辑岗位'
    },
    setform (postid) {
      console.log('填充人选')
      var postsort = 1
      for (let i = 0; i < this.personlist.length; i++) {
        if (postid === this.personlist[i].postId) {
          this.postForm.unitname = this.personlist[i].unitName
          let jobName = this.personlist[i].jobName.split(' ')[0]
          this.postForm.post = jobName
          let jobDescription = this.personlist[i].jobName.split(' ')[1]
          this.postForm.jobDescription = jobDescription
          // this.postForm.post = this.personlist[i].jobName
          this.postForm.postclass = this.personlist[i].jobLevel
          if (postsort === 1) {
            console.log('填充第1个人选')
            this.postForm.personid = this.personlist[i].id
            this.postForm.changeType = this.personlist[i].changeType
            this.postForm.oldunitname = this.personlist[i].candidateUnit
            this.postForm.personname = this.personlist[i].realName
            this.postForm.idcardNo = this.personlist[i].idcardNo
            let currentJob = this.personlist[i].currentJob.split(' ')[0]
            this.postForm.oldpost = currentJob
            let currentJobDescription = this.personlist[i].currentJob.split(' ')[1]
            this.postForm.currentJobDescription = currentJobDescription
            this.postForm.oldpostclass = this.personlist[i].currentLevel
            this.postForm.personid2 = ''
            this.postForm.oldunitname2 = ''
            this.postForm.personname2 = ''
            this.postForm.oldpost2 = ''
            this.postForm.oldpostclass2 = ''
            postsort++
          } else {
            console.log('填充第2个人选')
            this.postForm.personid2 = this.personlist[i].id
            this.postForm.changeType2 = this.personlist[i].changeType
            this.postForm.oldunitname2 = this.personlist[i].candidateUnit
            this.postForm.personname2 = this.personlist[i].realName
            this.postForm.idcardNo2 = this.personlist[i].idcardNo
            let currentJob = this.personlist[i].currentJob.split(' ')[0]
            this.postForm.oldpost2 = currentJob
            let currentJobDescription = this.personlist[i].currentJob.split(' ')[1]
            this.postForm.currentJobDescription2 = currentJobDescription
            this.postForm.oldpostclass2 = this.personlist[i].currentLevel
          }
        }
      }
    },
    del (id) {
      this.$confirm('确定要删除该人选吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .get(this.$http.defaults.selectionAPI + `api/change/deleteCandidatePerson?id=` + id)
          .then(response => {
            if (response.data.success) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              if (response.data.result === 0) {
                this.$router.push({path: '/selection/dongyi/0'})
                this.personlist = []
              } else {
                this.getpersonlist()
              }
            } else {
              this.$message({
                message: '删除失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            this.$message({
              message: '网络删除失败:' + error,
              type: 'error'
            })
          })
      }).catch(() => {
        console.log('已取消删除')
      })
    },
    getlastid () {
      var lastid = 0
      console.log(this.personlist.length)
      if (this.personlist && this.personlist.length > 0) {
        lastid = this.personlist[0].id
        this.personlist.forEach(element => {
          if (lastid < element.id) { lastid = element.id }
        })
      }
      return lastid
    },
    getlastpostid () {
      var lastpostid = 0
      console.log(this.personlist.length)
      if (this.personlist && this.personlist.length > 0) {
        lastpostid = this.personlist[0].postid
        this.personlist.forEach(element => {
          if (lastpostid < element.postid) { lastpostid = element.postid }
        })
      }
      return lastpostid
    },
    addperson2list (postnum) {
      // postnum=1 只保存第一个人选信息
      console.log('idcardNo')
      console.log(this.postForm.idcardNo)
      console.log('idcardNo2')
      console.log(this.postForm.idcardNo2)

      let post = {}
      let person1 = {}
      if (this.$route.params.id === '0') {
        post = {
          // dataCreateUserId: 0, // 获取用户id后传此参数
          // dataUpdateUserId: 0,
          jobLevel: this.postForm.postclass,
          jobName: this.postForm.post + ' ' + this.postForm.jobDescription,
          unitName: this.postForm.unitname
        }
        person1 = {
          changeType: this.postForm.changeType,
          candidateUnit: this.postForm.oldunitname,
          currentJob: this.postForm.oldpost + ' ' + this.postForm.currentJobDescription,
          currentLevel: this.postForm.oldpostclass,
          // dataCreateUserId: 0, // 获取用户id后传此参数
          // dataUpdateUserId: 0,
          idcardNo: this.postForm.idcardNo,
          realName: this.postForm.personname
        }
      } else {
        post = {
          busChangeProposalId: parseInt(this.$route.params.id),
          // dataCreateUserId: 0, // 获取用户id后传此参数
          // dataUpdateUserId: 0,
          jobLevel: this.postForm.postclass,
          jobName: this.postForm.post,
          unitName: this.postForm.unitname
        }
        person1 = {
          busChangeProposalId: parseInt(this.$route.params.id),
          changeType: this.postForm.changeType,
          candidateUnit: this.postForm.oldunitname,
          currentJob: this.postForm.oldpost + ' ' + this.postForm.currentJobDescription,
          currentLevel: this.postForm.oldpostclass,
          // dataCreateUserId: 0, // 获取用户id后传此参数
          // dataUpdateUserId: 0,
          idcardNo: this.postForm.idcardNo,
          realName: this.postForm.personname
        }
      }
      let persons = []
      persons.push(person1)
      if (postnum !== 1) {
        if (this.postForm.oldunitname2 && this.postForm.personname2) {
          let person2 = {}
          if (this.$route.params.id === '0') {
            person2 = {
              busPostId: this.editpostid,
              changeType: this.postForm.changeType2,
              candidateUnit: this.postForm.oldunitname2,
              currentJob: this.postForm.oldpost2 + ' ' + this.postForm.currentJobDescription2,
              currentLevel: this.postForm.oldpostclass2,
              // dataCreateUserId: 0, // 获取用户id后传此参数
              // dataUpdateUserId: 0,
              idcardNo: this.postForm.idcardNo2,
              realName: this.postForm.personname2
            }
          } else {
            person2 = {
              busChangeProposalId: parseInt(this.$route.params.id),
              busPostId: this.editpostid,
              changeType: this.postForm.changeType2,
              candidateUnit: this.postForm.oldunitname2,
              currentJob: this.postForm.oldpost2 + ' ' + this.postForm.currentJobDescription2,
              currentLevel: this.postForm.oldpostclass2,
              // dataCreateUserId: 0, // 获取用户id后传此参数
              // dataUpdateUserId: 0,
              idcardNo: this.postForm.idcardNo2,
              realName: this.postForm.personname2
            }
          }
          persons.push(person2)
        }
      }
      this.savepostssubmit(post, persons)
    },
    editperson2list (postnum) {
      // postnum=1 只保存第一个人选信息
      let post = {
        id: this.editpostid,
        busChangeProposalId: parseInt(this.$route.params.id),
        // dataCreateUserId: 0, // 获取用户id后传此参数
        // dataUpdateUserId: 0,
        jobLevel: this.postForm.postclass,
        jobName: this.postForm.post,
        unitName: this.postForm.unitname
      }
      let person1 = {
        id: this.postForm.personid,
        busChangeProposalId: parseInt(this.$route.params.id),
        busPostId: this.editpostid,
        changeType: this.postForm.changeType,
        candidateUnit: this.postForm.oldunitname,
        currentJob: this.postForm.oldpost + ' ' + this.postForm.currentJobDescription,
        currentLevel: this.postForm.oldpostclass,
        // dataCreateUserId: 0, // 获取用户id后传此参数
        // dataUpdateUserId: 0,
        idcardNo: this.postForm.idcardNo,
        realName: this.postForm.personname
      }
      let persons = []
      persons.push(person1)
      if (postnum !== 1) {
        if (this.postForm.oldunitname2 && this.postForm.personname2) {
          let person2 = {}
          if (this.postForm.personid2 === '') {
            person2 = {
              busChangeProposalId: parseInt(this.$route.params.id),
              busPostId: this.editpostid,
              changeType: this.postForm.changeType2,
              candidateUnit: this.postForm.oldunitname2,
              currentJob: this.postForm.oldpost2 + ' ' + this.postForm.currentJobDescription2,
              currentLevel: this.postForm.oldpostclass2,
              // dataCreateUserId: 0, // 获取用户id后传此参数
              // dataUpdateUserId: 0,
              idcardNo: this.postForm.idcardNo2,
              realName: this.postForm.personname2
            }
          } else {
            person2 = {
              id: this.postForm.personid2,
              busChangeProposalId: parseInt(this.$route.params.id),
              busPostId: this.editpostid,
              changeType: this.postForm.changeType2,
              candidateUnit: this.postForm.oldunitname2,
              currentJob: this.postForm.oldpost2 + ' ' + this.postForm.currentJobDescription2,
              currentLevel: this.postForm.oldpostclass2,
              // dataCreateUserId: 0, // 获取用户id后传此参数
              // dataUpdateUserId: 0,
              idcardNo: this.postForm.idcardNo2,
              realName: this.postForm.personname2
            }
          }
          persons.push(person2)
        }
      }
      console.log('idcardNo')
      console.log(this.postForm.idcardNo)
      console.log('idcardNo2')
      console.log(this.postForm.idcardNo2)
      console.log(JSON.stringify(persons))
      this.savepostssubmit(post, persons)
    },
    savepostssubmit (post, persons) {
      let para = {
        // currentUserId: 0,
        files: [],
        post: post,
        persons: persons
      }
      this.postFormLoading = true
      this.$http
        .post(this.$http.defaults.selectionAPI + `api/change/saveTemporaryPostAndPersons`, para)
        .then(response => {
          if (response.data.success) {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.postFormLoading = false
            this.postFormVisible = false
            if (this.$route.params.id === '0') {
              this.$router.push({path: '/selection/dongyi/' + response.data.result.id})
              this.listLoading = true
              this.getpersonlist()
            } else {
              this.listLoading = true
              this.getpersonlist()
            }
          } else {
            this.$message({
              message: '保存失败:' + response.data.message,
              type: 'error'
            })
            this.postFormLoading = false
          }
        })
        .catch(error => {
          this.$message({
            message: '网络保存失败:' + error,
            type: 'error'
          })
          this.postFormLoading = false
        })
    },
    saveperson2list (postnum) {
      console.log('this.editpostid:' + this.editpostid)
      if (this.editpostid === 0) {
        this.addperson2list(postnum)
      } else {
        this.editperson2list(postnum)
      }
    },
    checkperson2 () {
      if (this.postForm.oldunitname2 && this.postForm.personname2 && this.postForm.idcardNo2 && this.postForm.oldunitname2 !== '' && this.postForm.personname2 !== '' && this.postForm.idcardNo2 !== '') {
        return true
      } else {
        if ((!this.postForm.oldunitname2 || this.postForm.oldunitname2 === '') && (!this.postForm.personname2 || this.postForm.personname2 === '') && (!this.postForm.idcardNo2 || this.postForm.idcardNo2 === '')) {
          return true
        }
      }
    },
    postFormSubmit () {
      this.$refs['postForm'].validate((valid) => {
        if (valid) {
          // 验证岗位单位是否存在
          this.postFormLoading = true
          // this.$http
          //   .post(`/api/selection/checkunitname/`, this.postForm.unitname)
          //   .then(response => {
          //     this.postFormLoading = false
          //     if (response.data.result) {
          // if (this.postForm.postclass === '' && this.postForm.post === '') {
          //   this.$message({
          //     type: 'warning',
          //     message: '岗位职务和职级不能同时为无调整'
          //   })
          //   this.postFormLoading = false
          // } else {
          if (this.checkperson2()) { // 检查人选二信息是否完整或者全部未填写
            this.saveperson2list()
          } else { // 如果填写了人选二信息但并不完整时，弹出确认框，选是只保存第一人选，选否返回表单补充填写不提交
            this.$confirm('人选二信息不完整，是否只保存人选一?', '提示', {
              confirmButtonText: '是',
              cancelButtonText: '否',
              type: 'warning'
            }).then(() => {
              this.saveperson2list(1)
            }).catch(() => {
              this.postFormLoading = false
              this.$message({
                type: 'warning',
                message: '未保存岗位人选信息，如果有两个人选请将人选二信息补充完整后提交'
              })
              console.log('已取消提交')
            })
          }
          // }
        }
      })
      // .catch(error => {
      //   this.$message({
      //     message: '获取失败:' + error,
      //     type: 'error'
      //   })
      //   this.postFormLoading = false
      // })
      //   } else {
      //     console.log('表单验证失败')
      //     return false
      //   }
      // })
    },
    saveposts () {
      if (this.personlist.length > 0) {
        this.savelist()
      } else {
        this.$message.error('请至少录入一条岗位信息！')
      }
    },
    savelist () {
      let para = {
        // currentUserId: 0,
        changeProposalId: parseInt(this.$route.params.id)
      }
      this.loading1 = true
      this.$http
        .post(this.$http.defaults.selectionAPI + `api/change/confirmChange/`, Qs.stringify(para))
        .then(response => {
          this.loading1 = false
          if (response.data.success) {
            this.$message({
              message: '动议岗位人选保存成功',
              type: 'success'
            })
            this.step = 1
          } else {
            this.$message({
              message: '保存失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.loading1 = false
          console.log(error)
          this.$message({
            message: '保存失败:' + error,
            type: 'error'
          })
        })
    },
    exportdoc () {
      window.open(this.$http.defaults.baseURL + this.$http.defaults.selectionAPI + 'api/selection/document/exportChangeDoc?changeId=' + this.$route.params.id)
    },
    addpost () {
      this.postFormVisible = true
      this.postFormTitle = '新增岗位'
      this.editpostid = 0
    },
    tableresize (obj) {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      }
      obj.$nextTick(function () {
        obj.tableHeight = clientHeight - 165
      })
    },
    searchPerson (queryString, cb) {
      console.log('匹配人选姓名1：' + queryString)
      console.log('匹配人选单位1：' + this.postForm.oldunitname)
      return this.getpersons(this, queryString, cb, this.postForm.oldunitname)
    },
    searchPerson2 (queryString, cb) {
      return this.getpersons(this, queryString, cb, this.postForm.oldunitname2)
    },
    getpersons (self, queryString, cb, unitname) {
      console.log('匹配人选姓名：')
      console.log(queryString)
      console.log('匹配人选单位：')
      console.log(unitname)
      let para = {
        realname: queryString,
        unitname: unitname
      }
      console.log(para)
      self.$http
        .get(this.$http.defaults.selectionAPI + `api/selection/jiben`, {params: para})
        .then(function (response) {
          console.log('获取成功')
          var results = response.data.result
          let newArr = []
          results.forEach(function (item) {
            let obj = {'value': item.a0101, 'idno': item.a0184}
            newArr.push(obj)
          })
          cb(newArr)
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    querySearch (queryString, cb) {
      return this.getunits(this, queryString, cb)
    },
    getunits (self, queryString, cb) {
      let para = {
        unitname: queryString
      }
      self.$http
        .post(this.$http.defaults.selectionAPI + `api/busUnit/searchUnit`, para)
        .then(function (response) {
          console.log('获取成功')
          var results = response.data.result
          let newArr = []
          results.forEach(function (item) {
            let obj = {'value': item.unitName}
            newArr.push(obj)
          })
          cb(newArr)
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    getUnitType (post) {
      let unitname = ''
      switch (post) {
        case 0:
          unitname = this.postForm.unitname
          break
        case 1:
          unitname = this.postForm.oldunitname
          break
        case 2:
          unitname = this.postForm.oldunitname2
          break
      }
      console.log('正在匹配：' + unitname)
      let para = {
        unitname: unitname
      }
      if (unitname !== '') {
        this.postloading = true
        this.$http
          .post(this.$http.defaults.selectionAPI + `api/busUnit/searchUnit`, para)
          .then(response => {
            let results = response.data.result
            let para = {}
            if (results.length > 0) {
              let unit = results.find(item => item.unitName === unitname)
              if (unit) {
                console.log('找到了：' + unitname + ' 类型为' + unit.unitTypeName)
                para = { unitTypeName: unit.unitTypeName }
              }
            }
            this.$http
              .post(this.$http.defaults.selectionAPI + `api/selection/syspost/list `, para)
              .then(response => {
                this.postloading = false
                switch (post) {
                  case 0:
                    this.postlist = response.data
                    break
                  case 1:
                    this.postlist1 = response.data
                    break
                  case 2:
                    this.postlist2 = response.data
                    break
                }
              })
              .catch(function (error) {
                this.postloading = false
                console.log(error)
              })
          })
          .catch(function (error) {
            this.postloading = false
            console.log(error)
          })
      } else {
        switch (post) {
          case 0:
            this.postlist = []
            break
          case 1:
            this.postlist1 = []
            break
          case 2:
            this.postlist2 = []
            break
        }
      }
    },
    savedongyi () {
      this.$refs['dongyiForm'].validate((valid) => {
        if (valid) {
          for (let i = 0; i < this.personlist.length; i++) {
            if (!this.personlist[i].passed) {
              this.$message({
                message: '请将本次动议全部人选动议结果填写完整',
                type: 'error'
              })
              return false
            }
          }
          this.submitdongyi(2)
          // this.$confirm('本次党组会动议是否完成?', '提示', {
          //   confirmButtonText: '是，进入下一环节',
          //   cancelButtonText: '否，暂存',
          //   type: 'warning'
          // }).then(() => {
          //   this.submitdongyi(2)
          // }).catch(() => {
          //   this.submitdongyi(1)
          // })
        }
      })
    },
    submitdongyi (state) {
      let meeting = {
        // dataCreateUserId: 0,
        // dataDeleted: 0,
        // dataOrder: 0,
        // dataUpdateUserId: 0,
        // dataVersion: 0,
        id: parseInt(this.$route.params.id),
        leader2Opionion: this.dongyiForm.sileader,
        leaderOpinion: this.dongyiForm.buleader,
        meetingNumber: this.dongyiForm.meetnum,
        meetingTime: this.dongyiForm.meetdate,
        state: state
      }
      let persons = []
      for (let i = 0; i < this.personlist.length; i++) {
        let person = {
          busChangeProposalId: parseInt(this.$route.params.id),
          busPostId: this.personlist[i].postid,
          changeType: this.personlist[i].changeType,
          candidateUnit: this.personlist[i].oldunitname,
          currentJob: this.personlist[i].oldpost,
          currentLevel: this.personlist[i].oldpostclass,
          // // dataCreateUserId: 0,
          // dataDeleted: 0,
          // dataOrder: 0,
          // dataUpdateUserId: 0,
          // dataVersion: 0,
          id: this.personlist[i].id,
          idcardNo: this.personlist[i].idcardNo,
          realName: this.personlist[i].personname,
          state: 1,
          stateAfterChange: 0,
          stateChangeResult: this.personlist[i].passed
        }
        persons.push(person)
      }
      let fileIds = []
      for (let i = 0; i < this.files.length; i++) {
        fileIds.push(this.files[i].id)
      }
      let para = {
        // currentUserId: 0,
        meeting: meeting,
        persons: persons,
        files: fileIds
      }
      this.loading2 = true
      this.$http
        .post(this.$http.defaults.selectionAPI + `api/change/saveMeeting`, para)
        .then(response => {
          this.loading2 = false
          if (response.data.success) {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            if (this.inRoles('ROLE_chuzhang') && state === 2) {
              this.$router.push({path: '/selection/dongyihou/'})
            } else {
              this.$router.push({path: '/selection/dongyilist/'})
            }
          } else {
            this.$message({
              message: '保存失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.loading2 = false
          console.log(error)
          this.$message({
            message: '保存失败:' + error,
            type: 'error'
          })
        })
    },
    getpersonlist () {
      this.getNums()
      if (this.$route.params.id !== '0') {
        this.listLoading = true
        this.$http
          .post(this.$http.defaults.selectionAPI + `api/change/getChangeProposalPersons/`, Qs.stringify({id: parseInt(this.$route.params.id)}))
          .then(response => {
            if (response.data.success) {
              this.step = response.data.result.state
              this.personlist = response.data.result.persons
              // this.getList1()
              // this.getList2()
              // this.getList3()
              // for (let i = 0; i < response.data.result.persons.length; i++) {
              //   console.log(JSON.stringify(response.data.result.persons[i]))
              //   this.personlist.push(response.data.result.persons[i])
              //   this.personlist[i].currentJobDescription = response.data.result.persons[i].currentJob.split(' ')[1]
              //   this.personlist[i].currentJob = response.data.result.persons[i].currentJob.split(' ')[0]
              //   this.personlist[i].jobDescription = response.data.result.persons[i].jobName.split(' ')[1]
              //   this.personlist[i].jobName = response.data.result.persons[i].jobName.split(' ')[0]
              // }
              console.log(JSON.stringify(this.personlist))
              if (response.data.result.meeting) {
                this.dongyishowForm.sileader = response.data.result.meeting.leader2Opionion
                this.dongyishowForm.buleader = response.data.result.meeting.leaderOpinion
                this.dongyishowForm.meetnum = response.data.result.meeting.meetingNumber
                this.dongyishowForm.meetdate = response.data.result.meeting.meetingTime
              }
              this.downloadfiles = response.data.result.files
            } else {
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
            this.listLoading = false
          })
          .catch(error => {
            console.log(error)
            this.$message({
              message: '网络获取失败:' + error,
              type: 'error'
            })
            this.listLoading = false
          })
      }
    },
    getNums () {
      this.$http
        .get(this.$http.defaults.selectionAPI + `api/selection/statnum/change/getStatNum`)
        .then(response => {
          if (response.data.success) {
            this.countnum1 = response.data.result.countnum1
            this.countnum2 = response.data.result.countnum2
            this.countnum3 = response.data.result.countnum3
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    }
  },
  mounted () {
    this.getChangeType()
    // this.getjob()
    this.getjobLevel()
    this.getpersonlist()
    this.tableresize(this)
    let _this = this
    window.onresize = function windowResize () {
      // 通过捕获系统的onresize事件触发我们需要执行的事件
      _this.tableresize(_this)
    }
  }
}
</script>
<style>
  #selectionlist .wboxnoborder .el-table{
    border: #95B8E7 solid 1px;
  }
  #selectionlist .wboxnoborder .el-table th{
    font-weight: normal;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
    text-align: center;
    border-right: #95B8E7 solid 1px;
    border-bottom: #95B8E7 solid 1px;
    min-height: 30px;
    line-height:30px;
  }
  #selectionlist .wboxnoborder .el-table td, .el-table th{
    padding:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体';
    text-align: center;
  }
  #selectionlist .el-table__row{
    height: 50px;
  }
  #selectionlist .el-upload-list{
    width: 700px !important;
  }
</style>
<style scoped>
  h1{
    font-size:var(--size16) !important;
    font-weight: bolder;
    height: 30px;
    border-bottom: 1px solid #95B8E7;
    font-family: '宋体';
    line-height: 30px;
    color: #000;
    padding-left:10px;
    background-image: linear-gradient(to bottom , #EEF4FF, #E0ECFF);
    margin:0;
  }
  .el-pagination{
    float: left;
    padding:7px 10px;
  }
  .wboxs{
    padding:5px 15px;
    width: calc(100% - 30px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
  #selectionlist .wboxnoborder{
    padding:0;
    width: calc(100% - 0px);
    background: #fff;
    margin:0 10px;
    overflow: hidden;
  }
</style>
